﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using WMPLib;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using androidpost.Utils;
using System.Threading;
using androidpost.Object;
using System.Diagnostics;


namespace androidpost
{
    public partial class ControlMusic : Form
    {
        int code_control = 0;
        Boolean isStartThread = true;
        Boolean isFirstLoad = true;
        string mydir;
        JObject sent1;

        public ControlMusic()
        {
            InitializeComponent();


        }

        private void openfile_Click(object sender, EventArgs e)
        {
            mydir=Utils1.getDirName();
            if (mydir!=null)  CreatePlayLis(mydir);
           
        }

        private void CreatePlayLis(String folder)

            {
            
                Image img = Image.FromFile("music.png");
                panelPlaylist.Width = 200;
                panelWMP.Padding = new Padding(0,0,200,0);
                Application.DoEvents();
               
                var jsonarray = new JArray();
                lbPlaylist.Items.Clear();
                string myPlaylist = "sample";

                WMPLib.IWMPPlaylist pl;
                WMPLib.IWMPPlaylistArray plItems;
                plItems = wmp1.playlistCollection.getByName(myPlaylist);
                pl = wmp1.playlistCollection.newPlaylist(myPlaylist);

                DirectoryInfo dir = new DirectoryInfo(folder);
                FileInfo[] files = dir.GetFiles(Utils1.readFomat(), SearchOption.AllDirectories);
                int mid=0;
                foreach (FileInfo file in files)
                {
                    string musicFile01 = file.FullName;
                    string mName = file.Name;

                    if (Utils1.isMediaFile(musicFile01))
                    {
                         lbPlaylist.Items.Add(new testexListBox.exListBoxItem(mid,mName,"nodetail",img));
                    WMPLib.IWMPMedia m1 = wmp1.newMedia(musicFile01);
                    pl.appendItem(m1);
                    var jsonObject = new JObject();
                    jsonObject.Add("name",mName);
                    jsonarray.Add(jsonObject);
                    }
                   
                }

               

                 sent1 = new JObject();
                sent1.Add("list", jsonarray);

                communi.jsonPlaylist = jsonarray.ToString();
                wmp1.currentPlaylist = pl;
               
                
                Thread sentNotifi = new Thread(new ThreadStart(this.thSendNotifistring));
                sentNotifi.Start();

                lbPlaylist.AutoScrollOffset = new Point(lbPlaylist.AutoScrollOffset.X, 10);
                wmp1.Ctlcontrols.pause();

            }

       private void thSendNotifistring () 
       {
           if(sent1!=null)
            Network.NetworkSupport.sendControl(communi.code_control, Constant.TYPE_PLAYLIST, sent1.ToString());
        }



        private void lbPlaylist_DoubleClick(object sender, EventArgs e)
        {
            try
              {

                IWMPMedia med = wmp1.currentPlaylist.get_Item(lbPlaylist.SelectedIndices[0]);

                wmp1.Ctlcontrols.playItem(med);

                }

                catch (Exception)

                {

                }
        }


        private void clearList()
        {

            for (int i = 0; i < wmp1.currentPlaylist.count; i++)
            {
                IWMPMedia med = wmp1.currentPlaylist.get_Item(i);
                wmp1.currentPlaylist.removeItem(med);
            }

            lbPlaylist.Items.Clear();

        }


        private void ControlMusic_Load(object sender, EventArgs e)
        {
            Thread thGetcontrol = new Thread(new ThreadStart(this.lookControl));
            thGetcontrol.Start();
            panelPlaylist.Width = 1;
            panelWMP.Padding = new Padding(0);
            Application.DoEvents();

            //mo thu muc nhac
            mydir = Utils1.getDirName();
            if (mydir != null) CreatePlayLis(mydir);


            modRegistry modRegistry = new modRegistry();
            if (modRegistry.Read("firstrun") != "1")
            Process.Start("https://www.youtube.com/watch?v=JyHrnxRu92g");

            modRegistry abc123 = new modRegistry();
            abc123.Write("firstrun", "1");

        }

        private void ControlMusic_FormClosed(object sender, FormClosedEventArgs e)
        {
            isStartThread = false;
           
        }

        //----------------------method lookControl-----------------------------
        public void lookControl()
        {
           
            do
            {
                Thread.Sleep(Utils.Constant.REQUEST_TIMEOUT);
                   var ojcontrol= Network.NetworkSupport.getControl();
                  
                   if (isFirstLoad)
                   {
                       code_control = ojcontrol.code_control;
                       isFirstLoad = false;
                   }

                   if (code_control < ojcontrol.code_control)
                   {

                       exeControl(ojcontrol);
                       


                       
                    }
                  // Utils1.SynchronizedInvoke(full, delegate() { full.Text = code_control + ""; });
                  // Utils1.SynchronizedInvoke(button1, delegate() { button1.Text = ojcontrol.value + ""; });
                   code_control = ojcontrol.code_control;
            } while (isStartThread);
           
        }


        //----------------------method exeControl-----------------------------
        public void exeControl(OJControl oj)
        {
            
            int code_control1 = oj.code_control;
            int type1 = -1;
            string value1 = oj.value;
            try
            {
                type1 = Int32.Parse(oj.type);
            }
            catch (Exception)
            {

                type1 = -1;
            }
            
            //play selected
            if (type1==TypeAction.PLAY_SELECTED)
            {
                Utils1.log("value cexeControl type: PLAY_SELECTED");
                try
                {
                   int position = Int32.Parse(oj.value);
                   IWMPMedia med = wmp1.currentPlaylist.get_Item(position);
                    
                    wmp1.Ctlcontrols.playItem(med);
                   
                }
                catch (Exception e)
                {

                    Utils1.log("exeControl: error play: "+e );
                }
                
            }

            if (type1 == TypeAction.NEXT)
            {
                Utils1.log("value cexeControl type: NEXT");
                wmp1.Ctlcontrols.next();

            }

            if (type1 == TypeAction.PREVIEW)
            {
                Utils1.log("value cexeControl type: PREVIEW");
                wmp1.Ctlcontrols.previous();

            }

            if (type1 == TypeAction.PLAY)
            {
                Utils1.log("value cexeControl type: PLAY");
                try
                {
                    int value = Int32.Parse(oj.value);
                    if (value == 1)
                    {
                        wmp1.Ctlcontrols.play();
                    }
                    else wmp1.Ctlcontrols.pause();

                }
                catch (Exception e)
                {

                    Utils1.log("exeControl:(57345) error play: " + e);
                }

            }

            if (type1 == TypeAction.STOP)
            {
                Utils1.log("value cexeControl type: STOP");
                wmp1.Ctlcontrols.stop();

            }

            if (type1 == TypeAction.OPEN || type1 == TypeAction.CANCEL_SHUTDOWN)
            {
                Utils1.log("value cexeControl type: shutdown");
               

                ProcessStartInfo startInfo = new ProcessStartInfo("CMD.exe");
                Process p = new Process();
                startInfo.RedirectStandardInput = true;
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardOutput = false;
                startInfo.RedirectStandardError = true;


                p = Process.Start(startInfo);
                p.StartInfo.CreateNoWindow = true;
               

                  if (type1 == TypeAction.OPEN)
                  {
                       int value = Int32.Parse(oj.value);
                       p.StandardInput.WriteLine(@"shutdown -s -t " + value);
                      
                  }
            
                  else  p.StandardInput.WriteLine(@"shutdown /a");
                  
             
                p.Close();
              
                p.Dispose();
                Process[] prs = Process.GetProcesses();
                foreach (Process pr in prs)
                {
                    if (pr.ProcessName == "CMD.exe")
                    {

                        pr.Kill();

                    }

                }
                
           
            }




            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            panelPlaylist.Width = 1;
            panelWMP.Padding = new Padding(0);
            Application.DoEvents();
        }

        private void ControlMusic_FormClosing(object sender, FormClosingEventArgs e)
        {
            isStartThread = false;
            try
            {
                Environment.Exit(1);
            }
            catch (Exception)
            {

                throw;
            }

            Application.ExitThread();
            Application.Exit();
            
        }

       

        private void wmp1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
           
            if (e.newState==3)
            {
                for (int i = 0; i < wmp1.currentPlaylist.count; i++)
                {
                    if (wmp1.currentMedia.get_isIdentical(wmp1.currentPlaylist.get_Item(i))) lbPlaylist.SelectedIndex = i;
                }
            }
        }

        private void resendPlaylistToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Thread sentNotifi = new Thread(new ThreadStart(this.thSendNotifistring));
            sentNotifi.Start();
        }

        private void remotePPTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ControlPPT controlPPt = new ControlPPT();
            controlPPt.Show();
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            login fom1 = new login();
            fom1.ShowDialog();
            
        }

        private void showLogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormLog FormLog = new FormLog();
            FormLog.Show();
        }

       

        private void button1_Click_1(object sender, EventArgs e)
        {
            mydir = Utils1.getDirName();
            if (mydir != null) CreatePlayLis(mydir);
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("https://www.youtube.com/watch?v=JyHrnxRu92g");
        }

        private void menuFile_Click(object sender, EventArgs e)
        {
            mydir = Utils1.getDirName();
            if (mydir != null) CreatePlayLis(mydir);
        }
       

        
    }


}
